from PySide2.QtWidgets import QApplication, QMainWindow, QMessageBox
from PySide2.QtGui import QImage, QPainter, QPen  
from PySide2.QtCore import QPoint, Qt, QUrl, QSizeF, QTimer
from PySide2.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineProfile

import win32print
from PySide2.QtPrintSupport import QPrinter

# # 打印回调函数
# def print_completed(result):
#     pass

# # 开始打印小票
# def goto_print_litbill():
#     webview.page().print(printer, print_completed)

class MainWindow(QMainWindow):  
    def __init__(self):  
        super().__init__()  
        self.initUI()  
      
    def initUI(self):  
        self.setGeometry(100, 100, 400, 300)  
        self.setWindowTitle('POS 58 Printer')  
          
        self.webEngineView = QWebEngineView()  
        # self.webEngineView.setUrl(QUrl('file:///path/to/qrcode.png'))  # 替换为您的二维码图像路径  
        self.webEngineView.setUrl(QUrl('https://ncstatic.clewm.net/feres/a44fa42f_4b16ec36_1666157560.png'))  # 替换为您的二维码图像路径  

        self.setCentralWidget(self.webEngineView)  
      
    def printQRCode(self):  
        # 获取二维码图像  
        qrcode = self.webEngineView.page().currentFrame().documentElement().evaluateJavaScript('document.querySelector("#qrcode")')  
        image = qrcode.toImage()  # 将HTML元素转换为图像  
          
        # 调整图像大小并绘制到画布上  
        width = image.width() * 2  # 根据需要调整缩放比例  
        height = image.height() * 2  # 根据需要调整缩放比例  
        canvas = QImage(width, height, QImage.Format_RGB32)  
        canvas.fill(Qt.white)  # 设置画布背景色为白色  
        painter = QPainter(canvas)  # 创建画笔对象  
        pen = QPen(Qt.black, 2)  # 设置画笔颜色和宽度  
        painter.setPen(pen)  # 设置画笔属性  
        painter.drawImage(QPoint(0, 0), image, Qt.KeepAspectRatio)  # 在画布上绘制图像，保持比例不变  
        painter.end()  # 结束绘制操作  
          
        # 将图像发送到打印机（根据您的打印机型号和驱动程序进行适当的设置）  
        # ... your printer-specific code here ...  

        # win32print.SetDefaultPrinter("pos58")  #设置为默认打印机
        # printer = QPrinter()
        # printer.setPageSizeMM(QSizeF(80, 300))
        ##########必须延迟打印，否则网页还没加载，打印空白#########
        timer = QTimer()
        timer.timeout.connect(self.goto_print_litbill)
        timer.setSingleShot(True)
        timer.start(500)

    def goto_print_litbill(self):
        pass
        win32print.SetDefaultPrinter("pos58")  #设置为默认打印机
        printer = QPrinter()
        printer.setPageSizeMM(QSizeF(80, 300))
        self.webEngineView.print(printer)
      
if __name__ == '__main__':  
    app = QApplication([])  
    window = MainWindow()  
    window.show()  
    app.exec_()